package com.test.dababy.dababy_00_analytics.dababyhttp

import android.util.Log
import com.test.dababy.dababy_00_analytics.dababylogger.DababyFormatLogger
import com.test.dababy.dababy_00_http.Http_dababyLogger
import com.test.dababy.dababy_00_utils.DababyConfigs
import com.test.dababy.dababy_00_utils.DababyUtil
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.sql.DriverManager.println
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.TimeUnit

object DababyHttpHelper {

    /** 句柄 */
    private var mHttpPoolExecutordababy_dababy: DababyHttpPoolExecutor? = null

    /** 初始化执行线程 */
    private fun getHttpPoolExecutor_dababy(): DababyHttpPoolExecutor? {
        if (mHttpPoolExecutordababy_dababy == null) {
            val availableCoreSize = (Runtime.getRuntime().availableProcessors() / 2)
            val corePoolSize = if (availableCoreSize > 0) availableCoreSize else 1
            println("占用cpu核数：$corePoolSize")

            mHttpPoolExecutordababy_dababy = DababyHttpPoolExecutor(
                corePoolSize_dababy = corePoolSize,
                maximumPoolSize_dababy = corePoolSize,
                keepAliveTime_dababy = corePoolSize.toLong(),
                unit_dababy = TimeUnit.SECONDS,
                workQueue_dababy = LinkedBlockingDeque()
            ).apply {
                allowCoreThreadTimeOut(true)
            }
        }

        return mHttpPoolExecutordababy_dababy
    }

    /**
     * 保存数据
     *
     * @param targetUrl 目标路径
     * @param body 数据体
     */
    fun postData_dababy(targetUrl: String, body: String) {

        getHttpPoolExecutor_dababy()?.execute {
            var httpURLConnection: HttpURLConnection? = null;
            try {
                DababyFormatLogger.log_dababy(message = "targetUrl:$targetUrl")
                DababyFormatLogger.log_dababy(message = body)

                httpURLConnection = (URL(targetUrl).openConnection() as HttpURLConnection).apply {
                    setRequestProperty("Connection", "Keep-Alive")
                    setRequestProperty("Charset", "UTF-8")
                    setRequestProperty("Content-Type", "text/plain")
                    setRequestProperty("product", DababyConfigs.dababyProduct)

                    doOutput = true
                    useCaches = false
                    connectTimeout = 120000
                    doInput = true
                    requestMethod = "POST"
                    readTimeout = 180000

                    outputStream.write(body.toByteArray())
                    outputStream.flush()
                    outputStream.close()
                }

                with(httpURLConnection) {
                    val isSuccess = (responseCode == HttpURLConnection.HTTP_OK)
                    if (isSuccess) {

                        try {
                            // 获取输入流
                            val reader = BufferedReader(InputStreamReader(inputStream))
                            var line: String?
                            val response = StringBuilder()
                            while (reader.readLine().also { line = it } != null) {
                                response.append(line)
                            }
                            val decContent = DababyUtil.decryptDefault_dababy(response.toString())
                            if (decContent.length > 4000) {
                                var i = 0
                                while (i < decContent.length) {
                                    if (i + 4000 < decContent.length) {
                                        Log.i(
                                            Http_dababyLogger::class.java.simpleName + i,
                                            Http_dababyLogger.formatJson_dababy(
                                                decContent.substring(
                                                    i,
                                                    i + 4000
                                                )
                                            )
                                        )
                                    } else {
                                        Log.i(
                                            Http_dababyLogger::class.java.simpleName + i,
                                            Http_dababyLogger.formatJson_dababy(
                                                decContent.substring(
                                                    i,
                                                    decContent.length
                                                )
                                            )
                                        )
                                    }
                                    i += 4000
                                }
                            } else {
                                Log.i(
                                    Http_dababyLogger::class.java.simpleName,
                                    Http_dababyLogger.formatJson_dababy(decContent)
                                )
                            }

                            // 关闭读取器
                            reader.close()
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }

                        println("${responseCode}--${targetUrl}--post success!")
                        Log.d("", "${responseCode}--${targetUrl}--post success!")
                    } else {
                        println("${responseCode}--${targetUrl}--post fail!")
                        Log.d("", "${responseCode}--${targetUrl}--post fail!")
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace();
                println("post fail! ${e.localizedMessage}")

            } finally {
                httpURLConnection?.let {
                    try {
                        it.inputStream.close();
                        it.disconnect();
                    } catch (e: Exception) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}



